import os
import sys
from SeerDm import DmBase
from apscheduler.schedulers.background import BackgroundScheduler#后台调度器
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.triggers.interval import IntervalTrigger


class TaskManager():
    """任务管理器类"""
    def __init__(self,_dm=None,_path=''):
        #后台调度器
        self.jobstores = {'default':MemoryJobStore()}
        self.sched = BackgroundScheduler(jobstores=self.jobstores)
        self.sched.start()
        self.mainPath = _path
        self.dm = _dm
        self.taskData = self.loadTaskIni()
    
    def addTask(self,task_id='0',*data):
        """ 动态加载某任务.
            输出：加载的相应任务模块，失败返回None
        """
        sys.path.append(self.getTaskPath(num=0))
        #动态导入之前必须加入路径，否则找不到List
        try:
            del sys.modules['List.' + str(task_id) + ".job"]
        except:
            pass
        #pyJob = __import__('List.' + str(task_id) + ".job",fromlist=["*"])
        try:
            pyJob = __import__('List.' + str(task_id) + ".job",fromlist=["*"])
        except Exception as ex:
            print("\nERROR：任务List." + str(task_id) + ".job" + "错误添加失败\n")
            print("导入错误-->出现如下异常%s"%ex)
            _stre = str(ex)
            if _stre.find("invalid character in identifier") != -1:
                print("无效字符，我猜你用了中文的括号、引号、冒号？")
            if _stre.find("EOL while scanning string literal") != -1:
                print("你的字符串写的有问题，检查一下引号什么的")
            return None
        self.deleteTaskIni(task_id)
        trigger = IntervalTrigger(seconds=1)
        try:
            self.sched.add_job(pyJob.job,trigger,args=data,max_instances=100, id=task_id, name="task_name",jobstore="default")
        except ValueError:
            print("发现错误：猜测可能如下\n")
            print('def job(*args):     job函数缺少星号\n')
            print("self.addTask(_str,kkk=555)     添加任务时多给了参数\n")
            return None
        except Exception as ex:
            print("添加脚本错误-->出现如下异常%s"%ex)
            _stre = str(ex)
            if _stre.find("conflicts with an existing job") != -1:
                print("已经存在该任务请不要重复创建")
            if _stre.find("unindent does not match any outer indentation level") != -1:
                print("你的缩进有问题检查一下空格的数量")
            if _stre.find("has no attribute 'job'") != -1:
                print("没有在脚本里找到job函数,别瞎删东西")
            return None
        return pyJob
    
    def addOneTask(self,task_id=''):
        """根据YoSo的配置文件config.ini进行添加任务"""
        if str(task_id) != '':
            self.addTask(str(task_id))
            return True
        _path = self.getTaskPath(num=0) + '\\config.ini'
        _str = self.dm.readIni('config','task_id',_path)
        if _str != '':
            self.addTask(_str)
            return True
        return False
    
    def stopTask(self,task_id):
        """结束某任务"""
        try:
            self.sched.remove_job(task_id)
            print(str(task_id) + '任务已结束！')
        except:
            print("任务ID不存在")
    
    def pauseTask(self,task_id):
        """暂停某任务"""
        try:
            self.sched.pause_job(task_id)
            print(str(task_id) + '任务已暂停！')
        except:
            print("需要暂停的任务ID不存在")
    
    def resumeTask(self,task_id):
        """恢复某任务"""
        try:
            self.sched.resume_job(task_id)
            print(str(task_id) + '暂停任务已恢复！')
        except:
            print("需要恢复的任务ID不存在")
    
    def setTaskTime(self,task_id='0',_time = 1):
        """设置某任务的循环时间"""
        temp_trigger = IntervalTrigger(seconds=_time)
        self.sched.modify_job(job_id=task_id,trigger=temp_trigger)
    
    def setJobMaxInstances(self,task_id='0',instances=1):
        """设置该任务最大的同时执行数量"""
        self.sched.modify_job(job_id=task_id,max_instances=instances)
    
    def getRunTask(self,task_id='0'):
        """获取运行中的任务"""
        return self.sched.get_job(task_id)
    
    def getRunAllTask(self,isPrint=False):
        """ 获取所有运行中的任务
            isPrint=True时打印结果
        """
        jobs = self.sched.get_jobs()
        if isPrint==True:
            for i in jobs:
                print('\n'+str(i.id))
        return jobs
    
    def getTaskPath(self,task_id='0',num=0):
        """获取任务路径
        return:
            0获取当前工作目录路径
            1获取当前任务文件夹路径
            2获取当前状态的配置文件路径
            3获取当前任务的任务日志路径
            4截图功能ScreenSpy路径
            5获取Task目录
        """
        _path = self.mainPath
        if(num == 0):
            return _path
        elif(num == 1):
            return _path + "\\List\\" + task_id + "\\"
        elif(num == 2):
            return _path + "\\List\\" + task_id + "\\配置文件.ini"
        elif(num == 3):
            return _path + "\\List\\" + task_id + "\\任务日志.ini"
        elif(num == 4):
            return _path + "\\Screen\\"
        elif(num == 5):
            return _path + "\\List\\"
    
    def loadTaskIni(self):
        """ 加载目录中所有任务信息
            return:
                图点信息的列表合集
        """
        if self.dm == None:
            return None
        _dm: DmBase= self.dm
        _path = self.getTaskPath(num=5)
        _dirsList = []
        for root, dirs, files in os.walk(_path):  
            _dirsList = dirs
            break
        data01 = []#存储列表
        data02 = []#存储列表
        data03 = []#存储列表
        data04 = []#存储列表
        for _dir in _dirsList:
            _path = self.getTaskPath(str(_dir),num=1)
            _path2 = self.getTaskPath(str(_dir),num=2)
            isExists = os.path.exists(_path)
            if(isExists == False):
                continue
            for i in range(200):
                _dir2 = str(_dir)+'_'+str(i)#0000 0000_1
                _text = _dm.readIni(_dir2,'类型',_path2)
                if _text == '':
                    continue
                data01.append(_dir2)
                if(_text == '图片'):
                    _text2 = _dm.readIni(_dir2,'区域',_path2)
                    _text3 = _dm.readIni(_dir2,'资源',_path2)
                    _xy = _text2.split(',')
                    data01.append("图片")
                    data01.append(_xy)
                    data01.append(_path + _text3)
                elif(_text == '鼠标'):
                    _text2 = _dm.readIni(_dir2,'区域',_path2)
                    _xy = _text2.split(',')
                    data01.append("鼠标")
                    data01.append(_xy)
                data02.append(list(data01))
                data01.clear()#清空
            data03.append(_dir)
            data03.append(list(data02))
            data02.clear()#清空
            data04.append(list(data03))
            data03.clear()#清空
        return data04
    
    def deleteTaskIni(self,task_id='0'):
        """删除指定任务的日志"""
        if self.dm == None:
            return None
        _dm: DmBase = self.dm
        _path = self.getTaskPath(task_id,3)
        return _dm.deleteIni(task_id,_path)

    def Fun(self,task_id="0001",task_id2="0001_1",_isClickImage=1):
        """ 识图或点击
            _isClickImage： 1不点击此图
        """
        if self.taskData == None:
            return
        if self.dm == None:
            return None
        _dm: DmBase = self.dm
        _taskData = self.taskData
        _taskData2 = []
        _taskData3 = []
        for i in _taskData:
            if(task_id == i[0]):
                _taskData2 = i[1]
                break
        for i in _taskData2:
            if(task_id2 == i[0]):
                _taskData3 = i
                break
        try:
            _text = _taskData3[1]
        except:
            print("不存在：" + str(task_id2))
            return 0
        if(_text == "图片"):
            _xy = _taskData3[2]
            _text2 = _taskData3[3]
            dm_ret = _dm.findPic(int(_xy[0]),int(_xy[1]),int(_xy[2]),int(_xy[3]),_text2)
            if(_isClickImage != 1):#_isClickImage负责找图并原地点击
                if(dm_ret[0] != -1):
                    _dm.moveTo(dm_ret[1],dm_ret[2])
                    _dm.leftClick()
            return int(dm_ret[0]) + 1
        elif(_text == "鼠标"):
            _xy = _taskData3[2]
            _dm.moveTo(int(_xy[0]),int(_xy[1]))
            _dm.leftClick()
            return 9
    
    def Logs(self,isGet="get",task_id="0000",task_id2="变量名",_str="Set"):
        """操作任务日志--写入--获取"""
        if self.dm == None:
            return ''
        _dm: DmBase = self.dm
        _path = self.getTaskPath(task_id,3)
        if(isGet == "get"):#获取
            _text = _dm.readIni(task_id,task_id2,_path)
            return _text
        else:
            _dm.writeIni(task_id,task_id2,_str,_path)
            return '写入完成'
    
    
        
        